﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using QuizzMe.Helpers;
using QuizzMe.QuizzServiceRef;

namespace QuizzMe.Pages
{
    /// <summary>
    /// Quizz results page
    /// </summary>
    public partial class QuizzResult : BasePage
    {
        // Wall
        private const string ApplicationIcon = "http://perso.epita.fr/~muller_j/quizzme_icon.png";

        private int _goodAnswers;
        private int _badAnswers;
        private int _skipAnswers;

        private int _currentGoodAnswers;
        private int _currentBadAnswers;
        private int _currentSkipAnswers;

        private int _quizzScore;
        private Result _result;

        // Defy
        private Result _defyResult;
        
        private Storyboard _timer = new Storyboard();
        
        public int CurrentGoodAnswers
        {
            get { return _currentGoodAnswers; }
            set
            {
                if (_currentGoodAnswers != value)
                {
                    _currentGoodAnswers = value;
                    OnPropertyChanged("CurrentGoodAnswers");
                }
            }
        }

        public int CurrentBadAnswers
        {
            get { return _currentBadAnswers; }
            set
            {
                if (_currentBadAnswers != value)
                {
                    _currentBadAnswers = value;
                    OnPropertyChanged("CurrentBadAnswers");
                }
            }
        }

        public int CurrentSkipAnswers
        {
            get { return _currentSkipAnswers; }
            set
            {
                if (_currentSkipAnswers != value)
                {
                    _currentSkipAnswers = value;
                    OnPropertyChanged("CurrentSkipAnswers");
                }
            }
        }

        public int NbQuestions
        {
            get { return _goodAnswers + _skipAnswers + _badAnswers; }
        }

        public int QuizzScore
        {
            get { return _quizzScore; }
            set
            {
                if (_quizzScore != value)
                {
                    _quizzScore = value;
                    OnPropertyChanged("QuizzScore");
                }
            }
        }

        public string Infos { get; set; }

        public QuizzResult()
        {
            InitializeComponent();

            _timer = new Storyboard { Duration = TimeSpan.FromMilliseconds(20) };
            _timer.Completed += TimerCompleted;
        }

        // S'exécute lorsque l'utilisateur navigue vers cette page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (NavigationContext.QueryString.ContainsKey("r"))
            {
                Loading = true;
                ServiceClientHelper.Client.GetResultCompleted += ClientGetResultCompleted;
                ServiceClientHelper.Client.GetResultAsync(int.Parse(this.NavigationContext.QueryString["r"]));
            }
            else
            {
                _goodAnswers = 60;
                _badAnswers = 30;
                _skipAnswers = 10;

                QuizzScore = 15;
                OnPropertyChanged("NbQuestions");
            }

            CurrentGoodAnswers = 0;
            CurrentBadAnswers = 0;
            CurrentSkipAnswers = 0;

            _timer.Begin();
        }

        void ClientGetResultCompleted(object sender, GetResultCompletedEventArgs e)
        {
            ServiceClientHelper.Client.GetResultCompleted -= ClientGetResultCompleted;

            _result = e.Result;
            _goodAnswers = e.Result.goodAnswers.HasValue ? e.Result.goodAnswers.Value : 0;
            _badAnswers = e.Result.badAnswers.HasValue ? e.Result.badAnswers.Value : 0;
            _skipAnswers = e.Result.skipAnswers.HasValue ? e.Result.skipAnswers.Value : 0;
            OnPropertyChanged("NbQuestions");

            QuizzScore = e.Result.score;

            if (NavigationContext.QueryString.ContainsKey("defy"))
            {
                ServiceClientHelper.Client.GetResultCompleted += ClientDefyGetResultCompleted;
                ServiceClientHelper.Client.GetResultAsync(int.Parse(this.NavigationContext.QueryString["defy"]));
            }
            else
            {
                Loading = false;
                _timer.Begin();
            }
        }

        private void ClientDefyGetResultCompleted(object sender, GetResultCompletedEventArgs e)
        {
            ServiceClientHelper.Client.GetResultCompleted -= ClientDefyGetResultCompleted;

            _defyResult = e.Result;

            Loading = false;
            _timer.Begin();
        }

        private void TimerCompleted(object sender, EventArgs e)
        {
            bool changed = false;

            if (CurrentGoodAnswers != _goodAnswers)
            {
                ++CurrentGoodAnswers;
                changed = true;
            }
            if (CurrentBadAnswers != _badAnswers)
            {
                ++CurrentBadAnswers;
                changed = true;
            }
            if (CurrentSkipAnswers != _skipAnswers)
            {
                ++CurrentSkipAnswers;
                changed = true;
            }

            if (changed)
                _timer.Begin();
            else
            {
                if (_defyResult != null)
                {
                    if (_defyResult.score < _result.score)
                    {
                        Infos = "Congratulations, you win against " + _defyResult.User.userName;
                        OnPropertyChanged("Infos");
                    }
                    else
                    {
                        Infos = "Too bad, you lose against " + _defyResult.User.userName;
                        OnPropertyChanged("Infos");
                    }
                    publishDefyResultsButton.Visibility = Visibility.Visible;
                }
            }
        }

        private void ButtonOkClick(object sender, RoutedEventArgs e)
        {
            this.NavigateTo(new Uri("/Home", UriKind.Relative));
        }

        /// <summary>
        /// Defy friends on that quizz by publishing a message on the facebook wall
        /// </summary>
        private void ButtonPublishClick(object sender, RoutedEventArgs e)
        {
            var id = int.Parse(this.NavigationContext.QueryString["r"]);
            Dictionary<string, object> parameters = new Dictionary<string, object>
                                                            {
                                                                { "message", "I've just played at QuizzMe and I got " + QuizzScore + " ! Could you do better ? Just try !" },
                                                                { "link", "http://apps.facebook.com/quizzmefb/?defy=" + id },
                                                                { "picture", ApplicationIcon },
                                                                { "caption", "QuizzMe" },
                                                                { "description", "Test your knowledge !" }
                                                            };

            AuthHelper.Get.FacebookClient.PostAsync("/me/feed", parameters);

            publishButton.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// Recommand the quizz on the facebook wall
        /// </summary>
        private void ButtonRecommandClick(object sender, RoutedEventArgs e)
        {
            var id = int.Parse(this.NavigationContext.QueryString["r"]);
            Dictionary<string, object> parameters = new Dictionary<string, object>
                                                            {
                                                                { "message", "I've just played at QuizzMe and I got " + QuizzScore + " ! You should try, it was really interesting !" },
                                                                { "link", "http://apps.facebook.com/quizzmefb/?id=" + _result.quizzId },
                                                                { "picture", ApplicationIcon },
                                                                { "caption", "QuizzMe" },
                                                                { "description", "Test your knowledge !" }
                                                            };

            AuthHelper.Get.FacebookClient.PostAsync("/me/feed", parameters);

            recommandButton.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// Publish the defy results on the facebook wall 
        /// </summary>
        private void ButtonPublishDefyResultsClick(object sender, RoutedEventArgs e)
        {
            string ennemy = _defyResult.User.userName;
            string msg = string.Format("I've just played at QuizzMe against {0} and I got {1} !", ennemy, QuizzScore);

            if (_defyResult.score < _result.score)
            {
                msg += string.Format(" It's {0} more that him, I'm just too smart for you boy :D", _result.score - _defyResult.score);
            }
            else if (_defyResult.score == _result.score)
            {
                msg += " It's the same score that him !";                
            }
            else
            {
                msg += string.Format(" It's {0} less that him, he's just too smart for me :'(", _defyResult.score - _result.score);
            }
            msg += string.Format(" You too, try to defeat him !");

            Dictionary<string, object> parameters = new Dictionary<string, object>
                                                            {
                                                                { "message", msg },
                                                                { "link", "http://apps.facebook.com/quizzmefb/?defy=" + _defyResult.resultId },
                                                                { "picture", ApplicationIcon },
                                                                { "caption", "QuizzMe" },
                                                                { "description", "Test your knowledge !" }
                                                            };

            AuthHelper.Get.FacebookClient.PostAsync("/me/feed", parameters);

            publishDefyResultsButton.Visibility = Visibility.Collapsed;
        }
    }
}
